package com.chang.soul.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.fastjson.JSONObject;
import com.chang.soul.Listen.ExcelListener;
import com.chang.soul.bean.PaperAnalysisBean;
import com.chang.soul.bean.PaperAnalysisQueryForm;
import com.chang.soul.conf.JwtIgnore;
import com.chang.soul.service.PaperAnalysisService;
import com.chang.soul.util.Result;
import com.chang.soul.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/paperAnalysis")
@Api("量表结果分析接口")
public class PaperAnalysisController {
    @Autowired
    PaperAnalysisService paperAnalysisService;

    /**
     * 测试Excel导入
     */
    @ApiOperation(value = "文件导入", notes = "无需Token", httpMethod = "POST")
    @PostMapping("/importAnalysisExcel")
    @JwtIgnore
    public Result importAnalysisExcel(@RequestParam("file") MultipartFile file) {

        try {
            File targetFile = new File(System.getProperty("user.dir") + "/analysisFile" + "/analysisFile.xlsx");
            file.transferTo(targetFile);

            ExcelListener excelListener = new ExcelListener();

            // 工作簿，对应的是一个excel文件
            ExcelReaderBuilder readWorkBook = EasyExcel.read(System.getProperty("user.dir") + "/analysisFile" + "/analysisFile.xlsx",
                    PaperAnalysisBean.class, excelListener);
            // 工作表，对应一个sheet。 一个工作簿里面可以含有多个工作表
            ExcelReaderSheetBuilder sheet = readWorkBook.sheet();
            //读
            sheet.doRead();

            //获取数据
            List<Object> list = excelListener.getDatas();
            System.out.println(list);
            PaperAnalysisBean paperAnalysisBean = new PaperAnalysisBean();
            for (int i = 0; i < list.size(); i++) {
                paperAnalysisBean = (PaperAnalysisBean) list.get(i);
                if (!paperAnalysisService.insertAnalysis(paperAnalysisBean)) {
                    return ResultUtil.error("insert fail!");
                }
            }
            return ResultUtil.success("insert success!");
        } catch (Exception e) {
            System.out.println(e);
            return ResultUtil.error("导入失败");
        }
        /**
         * 参考链接
         * https://www.jianshu.com/p/78cc1729fbd1
         */
    }

    @ApiOperation(value = "通过id 删除分析结果",notes = "无需token",httpMethod = "GET")
    @GetMapping("/deleteAnalysisById")
    @JwtIgnore
    public Result deleteAnalysisById(@RequestParam("id")Integer id ){
        boolean flage = paperAnalysisService.deleteAnalysisById(id);
        if(!flage){
            return ResultUtil.error("delete paper analysis fail");
        }
        return ResultUtil.success("delete paper analysis success!");
    }

    @ApiOperation(value = "分页模糊查询 量表分析结果", notes = "无需token", httpMethod = "POST")
    @PostMapping("/getAllAnalysisList")
    @JwtIgnore
    public Result getAllAnalysisList(@Valid @RequestBody PaperAnalysisQueryForm paperAnalysisQueryForm) {
        Integer currentPage = paperAnalysisQueryForm.getCurrentPage();
        Integer pageSize = paperAnalysisQueryForm.getPageSize();
        currentPage = currentPage == null || currentPage <= 0 ? 1 : currentPage;
        pageSize = pageSize == null || pageSize <= 0 ? 1 : pageSize;
        Integer startNum = (currentPage - 1) * pageSize;
        paperAnalysisQueryForm.setCurrentPage(startNum);
        paperAnalysisQueryForm.setPageSize(pageSize);

        List<PaperAnalysisBean> list = paperAnalysisService.getAllAnalysisList(paperAnalysisQueryForm);
        int total = paperAnalysisService.getCountByAnalysisList(paperAnalysisQueryForm);
        JSONObject res = new JSONObject();
        res.put("currentPage", currentPage);
        res.put("pageSize", pageSize);
        res.put("totalCount", total);
        res.put("list", list);
        System.out.println(res);
        return ResultUtil.success(res);
    }

    @ApiOperation(value = "更新 量表结果 分析接口",notes = "无需token",httpMethod = "POST")
    @PostMapping("/updateAnalysis")
    @JwtIgnore
    public Result updateAnalysis(@Valid @RequestBody PaperAnalysisBean myPaperAnalysisBean){
        PaperAnalysisBean paperAnalysisBean = paperAnalysisService.getAnalysisByPaperId(myPaperAnalysisBean.getPaperId());

        paperAnalysisBean.setFirstScore(myPaperAnalysisBean.getFirstScore());
        paperAnalysisBean.setFirstAnalysis(myPaperAnalysisBean.getFirstAnalysis());

        paperAnalysisBean.setSecondScore(myPaperAnalysisBean.getSecondScore());
        paperAnalysisBean.setSecondAnalysis(myPaperAnalysisBean.getSecondAnalysis());

        paperAnalysisBean.setThirdScore(myPaperAnalysisBean.getThirdScore());
        paperAnalysisBean.setThirdAnalysis(myPaperAnalysisBean.getThirdAnalysis());

        paperAnalysisBean.setFourthScore(myPaperAnalysisBean.getFourthScore());
        paperAnalysisBean.setFourthAnalysis(myPaperAnalysisBean.getFourthAnalysis());

        paperAnalysisBean.setFifthScore(myPaperAnalysisBean.getFifthScore());
        paperAnalysisBean.setFifthAnalysis(myPaperAnalysisBean.getFifthAnalysis());

        paperAnalysisBean.setSixthScore(myPaperAnalysisBean.getSixthScore());
        paperAnalysisBean.setSixthAnalysis(myPaperAnalysisBean.getSixthAnalysis());

        paperAnalysisBean.setSeventhScore(myPaperAnalysisBean.getSeventhScore());
        paperAnalysisBean.setSeventhAnalysis(myPaperAnalysisBean.getSeventhAnalysis());

        if (paperAnalysisService.updateAnalysis(paperAnalysisBean)) {
            return ResultUtil.success("update paper analysis success");
        } else {
            return ResultUtil.error("update paper analysis fail");
        }

    }

    // 文件上传 （可以多文件上传）
    @ApiOperation(value = "分析结果文件上传", notes = "无需token", httpMethod = "POST")
    @PostMapping("/upload")
    @JwtIgnore
    public Result fileUploads(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {

        String filePath = "G:\\analysisFile\\";
        // 日志打印
        Logger log = LoggerFactory.getLogger("UploadPaperAnalysisController");

        // 获取上传的文件名称
        String fileName = file.getOriginalFilename();
        File file1 = new File(filePath);
        //判断上传文件的保存目录是否存在
        if (!file1.exists() && !file1.isDirectory()) {
            System.out.println(filePath + "目录不存在，需要创建");
            //创建目录
            file1.mkdir();
        }

        // 得到文件保存的位置以及新文件名
        File dest = new File(filePath + fileName);
        try {
            // 上传的文件被保存了
            file.transferTo(dest);
            // 打印日志
            log.info("上传成功，当前上传的文件保存在 {}", filePath + fileName);
            // 自定义返回的统一的 JSON 格式的数据，可以直接返回这个字符串也是可以的。
            return ResultUtil.success("文件上传成功");
        } catch (IOException e) {
            log.error(e.toString());
        }
        // 待完成 —— 文件类型校验工作
        return ResultUtil.error("上传错误");
    }

    /**
     * 下载文件接口
     */
    @ApiOperation(value = "下载文件接口", notes = "需Token", httpMethod = "GET", produces = "application/octet-stream")
    @GetMapping("/download")
    @JwtIgnore
    public String down(@RequestParam(value = "filename")String filename, HttpServletResponse response) throws UnsupportedEncodingException {
        //获取项目的相对路径
//        String property = System.getProperty("user.dir");
//        String path = property + "/src/main/resources/static/";
//
////        String filename = "playlist.xlsx";

        String filePath = "G:\\analysisFile\\";
        File file = new File(filePath + "/" + filename);
        if (file.exists()) {
            System.out.println(filePath + "/" + filename + "存在");
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
                return "success!";
            } catch (Exception e) {
                e.printStackTrace();
                return "fail!";
            }
        } else {
            return "fail!";
        }
    }


}


